<!-- 添加商铺 -->
<template>
  <div id="app">
    <top-header></top-header>
    <div class="el-form">
      <el-row style="margin: 20px">
        <el-col :span="12">
          <el-form
            :model="form"
            :rules="rules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="店铺名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-autocomplete
                v-model="form.address"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入地址"
                style="width: 100%"
                @select="addressSelect"
              ></el-autocomplete>
              <!-- <span>当前城市：{{city.name}}</span> -->
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model.number="form.phone" maxlength="11"></el-input>
            </el-form-item>
            <el-form-item label="店铺简介" prop="description">
              <el-input v-model="form.description"></el-input>
            </el-form-item>
            <el-form-item label="店铺标语" prop="promotion_info">
              <el-input v-model="form.promotion_info"></el-input>
            </el-form-item>
            <el-form-item label="店铺分类">
              <el-cascader
                v-model="selectedCategory"
                :options="categoryOptions"
                :props="{ checkStrictly: true }"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
            <!-- 店铺特点 -->
            <el-form-item label="店铺特点" style="width: 600px">
              <el-switch
                inactive-text="品牌保证"
                v-model="form.is_premium"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
              >
              </el-switch>
              <el-switch
                inactive-text="蜂鸟专送"
                v-model="form.delivery_mode"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
              >
              </el-switch>
              <el-switch
                inactive-text="新开店铺"
                v-model="form.newshop"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
              >
              </el-switch>
            </el-form-item>

            <el-form-item style="width: 600px">
              <el-switch
                inactive-text="外卖保"
                v-model="form.bao"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
              >
              </el-switch>
              <el-switch
                inactive-text="准时达"
                v-model="form.zhun"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
              >
              </el-switch>
              <el-switch
                inactive-text="开发票"
                v-model="form.piao"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
              >
              </el-switch>
            </el-form-item>
            <!-- 店铺特点结束 -->
            <el-form-item label="配送费">
              <template>
                <el-input-number
                  v-model="form.float_delivery_fee"
                  @change="changePrice1"
                  :min="0"
                  :max="10"
                  label="描述文字"
                ></el-input-number>
              </template>
            </el-form-item>

            <el-form-item label="起送价">
              <template>
                <el-input-number
                  v-model="form.float_minimum_order_amount"
                  @change="changePrice2"
                  :min="0"
                  :max="90"
                  label="描述文字"
                ></el-input-number>
              </template>
            </el-form-item>

            <el-form-item label="营业时间">
              <el-time-select
                placeholder="起始时间"
                v-model="form.startTime"
                :picker-options="{
                  start: '06:30',
                  step: '00:10',
                  end: '18:30',
                }"
              >
              </el-time-select>
              <el-time-select
                placeholder="结束时间"
                v-model="form.endTime"
                :picker-options="{
                  start: '08:30',
                  step: '00:10',
                  end: '23:00',
                  minTime: form.startTime,
                }"
              >
              </el-time-select>
            </el-form-item>

            <el-form-item label="上传店铺头像">
              <el-upload
                class="avatar-uploader"
                :action="BASE_URL + 'v1/addimg/shop'"
                :show-file-list="false"
                :on-success="handleUserAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="form.image_path"
                  :src="baseImgPath + form.image_path"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传营业执照">
              <el-upload
                class="avatar-uploader"
                :action="BASE_URL + 'v1/addimg/shop'"
                :show-file-list="false"
                :on-success="handleBlicenceAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="form.business_license_image"
                  :src="baseImgPath + form.business_license_image"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传餐饮服务许可证">
              <el-upload
                class="avatar-uploader"
                 :action="BASE_URL + 'v1/addimg/shop'"
                :show-file-list="false"
                :on-success="handleCpermitAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="form.catering_service_license_image"
                  :src="baseImgPath + form.catering_service_license_image"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="优惠活动">
              <el-select
                v-model="activityValue"
                :placeholder="activityValue"
                @change="selectActivity"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-table :data="activities" style="min-width: 720px">
              <el-table-column label="活动标题" width="120" align="center">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{
                    scope.row.icon_name
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="活动名称" width="120" align="center">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="活动详情" width="360" align="center">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.detail }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="Delete(scope.$index)"
                    >删除</el-button
                  >
                  <!--   @click="handleDelete(scope.$index, scope.row)" -->
                </template>
              </el-table-column>
            </el-table>

            <el-form-item style="margin: 20px">
              <el-button
                type="primary"
                @click="submitForm('form')"
                style="margin-left: 150px"
                >立即创建</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>



<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import TopHeader from "./top-header";
import {updateShop,getShoplist,addShop,searchPlace,cityGuess,foodCategory} from "@/api/api"
import { BASE_URL, baseImgPath } from "@/config/env";
// import TopHeader from './top-header.vue';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    "top-header": TopHeader,
  },
  data() {
    //这里存放数据
    return {
      activities: [
        {
          icon_name: "减",
          name: "满减优惠",
          detail: "满30减5，满60减8",
        },
      ],
      preactivityValue:"",
       activityValue: "满减优惠",
      options: [
        {
          value: "满减优惠",
          label: " 满减优惠",
        },
        {
          value: "新用户立减",
          label: "新用户立减",
        },
        {
          value: "优惠大酬宾",
          label: "优惠大酬宾",
        },
        {
          value: "进店领券",
          label: "进店领券",
        },
      ],
      

     
      
      
      selectedCategory: ["快餐便当", "简餐"],
   
      categoryOptions:[],
      form: {
         
        name: "",//店铺名称
        address: "",//地址
        latitude: '',
				longitude: '',
        phone: "",//电话号码
        description: "",//介绍
        promotion_info: "",//店铺标语
        float_delivery_fee: "5",//运费
        float_minimum_order_amount: "20",//起步价
        is_premium: true,
        delivery_mode: true,
        newshop: true,
        bao: true,
        zhun: true,
        piao: true,
        image_path: "",
       business_license_image: "",
       catering_service_license_image: "",
       startTime: "",
       endTime: "",
      },
       baseImgPath,
       BASE_URL,
      rules: {
        name: [
          { required: true, message: "请输入店铺名称", tigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入详细的地址", tigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入联系电话" },
          { type: "number", message: "电话号码必须是数字" },
        ],
      },
      city:{},
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async initData(){
 try {
        this.city = await cityGuess();
        const categories = await foodCategory();
        console.log("categories",categories)
        categories.forEach((item) => {
          if (item.sub_categories.length) {
            const addnew = {
              value: item.name,
              label: item.name,
              children: [],
            };
            item.sub_categories.forEach((subitem, index) => {
              if (index == 0) {
                return;
              }
              addnew.children.push({
                value: subitem.name,
                label: subitem.name,
              });
            });
            this.categoryOptions.push(addnew);
          }
        });
      } catch (err) {
        console.log(err);
      }
    },
    /* 查询城市地点 */
    async querySearchAsync(queryString,cb){
          if(queryString){
            try{
              const cityList = await searchPlace({keyword:queryString});
              if(cityList instanceof Array){
                cityList.map((item) =>{
                  item.value = item.address;
                  return item;
                });
                cb(cityList)
              }  
            }catch(err){
              console.log("这是个啥："+err)
            }
          }
    },
    /* 查询城市 */
     addressSelect(address) {
      this.form.latitude = address.latitude;
      this.form.longitude = address.longitude;
      console.log(this.form.latitude, this.form.longitude);
    },
    /* 上传图片 */
    handleChange: function (value) {
      console.log(value);
    },
    changePrice1: function (value) {
      console.log(value);
    },
    changePrice2: function (value) {
      console.log(value);
    },

    /* 上传用户头像 */
    handleUserAvatarSuccess(res, file) {
      this.form.image_path = res.image_path;
    },

    /* 上传营业执照 */
    handleBlicenceAvatarSuccess(res, file) {
      this.form.business_license_image =res.image_path;
    },

    /* 上传餐饮服务许可证 */
    handleCpermitAvatarSuccess(res, file) {
      this.form.catering_service_license_image = res.image_path;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

  
    /* 选择活动 */
    selectActivity() {
        
     console.log("pre"+this.preactivityValue)
    
      
      this.$prompt("请输入活动详情", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          if (value == null) {
            this.$message({
              type: "info",
              message: "请输入活动详情aaaaa",
            });
            return
          }
          let newObject = {};
          
          switch (this.activityValue) {
            case "满减优惠":
              newObject = {
                icon_name: "减",
                name: "满减优惠",
                detail: value,
              };
              break;
            case "优惠大酬宾":
              newObject = {
                icon_name: "特",
                name:"优惠大酬宾",
                detail: value,
              };
              break;
            case "新用户立减":
              newObject = {
                icon_name: "新",
                name: "新用户立减",
                description: value,
              };
              break;
            case "进店领券":
              newObject = {
                icon_name: "领",
                name: "进店领券",
                description: value,
              };
              break;
          }
          this.activities.push(newObject)
        })
        .catch(() => {
          console.log("后面的:" + this.activityValue + "2");
          this.$message({
            type: "info",
            message: "取消输入",
          
          });
         
        this. activityValue = this.preactivityValue
        });
      return;
    },
    /* 点击删除按钮 */
    Delete:function(index){
      // console.log(index)
      this.activities.splice(index,1)
    },
    /* 提交上传 */
    submitForm(formName){
      this.$refs[formName].validate(async (valid)=>{
        if(valid){
          console.log(this.form)
          // Object.assign方法用于对象的合并，将源对象（source）的所有可枚举属性，复制到目标对象（target）返回目标对象。
          Object.assign(this.form,{activities:this.activities},{category: this.selectedCategory.join("/"),})
           try {
             //addShop(this.form);返回promise
             //含有两个参数message和status
             let result = await addShop(this.form);
             if(result.status == 1){
               this.$message({
                 type:"success",
                 message:"终于添加成功了"
               });
               this.form = {
                  name: "",//店铺名称
                  address: "",//地址
                  latitude: '',
                  longitude: '',
                  phone: "",//电话号码
                  description: "",//介绍
                  promotion_info: "",//店铺标语
                  float_delivery_fee: "5",//运费
                  float_minimum_order_amount: "20",//起步价
                  is_premium: true,
                  delivery_mode: true,
                  newshop: true,
                  bao: true,
                  zhun: true,
                  piao: true,
                  image_path: "",
                  business_license_image: "",
                  catering_service_license_image: "",
                  startTime: "",
                  endTime: "",
               };
                this.selectedCategory = ["快餐便当", "简餐"];
                this.activities = [
                  {
                    icon_name: "减",
                    name: "满减优惠",
                    description: "满30减5，满60减8",
                  },
                ];

             } else {
               this.$message({
                 type:"error",
                  message:result.message,
               })
             }
             console.log(result)
           }catch(err){console.log(err);}
         }else {
             this.$notify.error({
               title:"错误",
                message: "请检查输入是否正确",
                });
             return false;
             }
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）               
  async created() {
     console.log(this.activities)
   
     console.log(addShop(this.form))

    //  console.log(this.selectedCategory.join("/"))
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initData();
    console.log("mounted:" + this.activityValue)
    this.preactivityValue = this.activityValue
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style  scoped>
.el-form {
  margin-left: 10%;
}

.avatar {
  width: 178px;
  height: 178px;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader-icon:hover {
  border-color: blue;
}
</style>